<template>
    <div>
      <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <i class="el-icon-lx-cascades"></i> 辞职申请列表
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="container">
        <div class="handle-box">
          <el-select v-model="query.status"
                     placeholder="状态"
                     clearable
                     size="medium"
                     class="handle-select mr10">
            <el-option v-for="(item, index) in resignStatus"
                       :key="index"
                       :value="item.value"
                       :label="item.label"></el-option>
          </el-select>
          <el-input v-model="query.name"
                    placeholder="姓名"
                    clearable
                    size="medium"
                    class="handle-input mr10"></el-input>
          <el-button type="primary"
                     icon="el-icon-search"
                     size="medium"
                     @click="handleSearch">搜索</el-button>
          <el-button type="primary"
                     icon="el-icon-download"
                     size="medium"
                     style="float: right"
                     @click="exportExcel">导出</el-button>
          <el-button type="primary"
                     icon="el-icon-document-add"
                     size="medium"
                     style="float: right"
                     @click="handleAdd">添加</el-button>
        </div>
        <el-table :data="tableData"
                  border
                  size="medium"
                  class="table"
                  ref="multipleTable"
                  header-cell-class-name="table-header">
          <el-table-column prop="id"
                           label="ID"
                           width="60"
                           align="left"></el-table-column>
          <el-table-column prop="staff_name"
                           label="姓名"></el-table-column>
          <el-table-column prop="staff.job_no"
                           min-width="80"
                           label="工号"></el-table-column>
          <el-table-column prop="staff.department_name"
                           min-width="140"
                           label="所在部门"></el-table-column>
          <el-table-column prop="staff_left_date"
                           min-width="120"
                           label="员工预期离职日期"></el-table-column>
          <el-table-column prop="final_left_date"
                           min-width="120"
                           label="最终确定离职日期"></el-table-column>
          <el-table-column prop="resign_reason"
                           min-width="140"
                           label="离职原因"></el-table-column>
          <el-table-column label="状态"
                           align="left">
            <template #default="scope">
              <el-tag v-if="scope.row.status === '新建'"
                      type="success">{{ scope.row.status }}</el-tag>
              <el-tag v-if="scope.row.status === '审批中'"
                      type="warning">{{ scope.row.status }}</el-tag>
              <el-tag v-if="scope.row.status === '同意'"
                      type="info">{{ scope.row.status }}</el-tag>
              <el-tag v-if="scope.row.status === '驳回'"
                      type="info">{{ scope.row.status }}</el-tag>
              <el-tag v-if="scope.row.status === '归档'"
                      type="danger">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at"
                           label="创建时间"></el-table-column>
          <el-table-column label="操作"
                           min-width="140"
                           align="left">
            <template #default="scope">
              <el-button type="text"
                         icon="el-icon-edit"
                         @click="handleEdit(scope.$index, scope.row)">编辑
              </el-button>
              <el-button type="text"
                         icon="el-icon-delete"
                         class="red"
                         @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination background
                         layout="total, prev, pager, next"
                         :current-page="query.pageIndex"
                         :page-size="query.pageSize"
                         :total="pageTotal"
                         @current-change="handlePageChange"></el-pagination>
        </div>
      </div>
  
      <!-- 编辑弹出框 -->
      <el-dialog :title="title"
                 v-model="editVisible"
                 width="40%">
        <el-form ref="formRef"
                 :rules="rules"
                 :model="form"
                 label-width="140px">
          <el-form-item label="选择员工"
                        prop="staff_id">
            <el-select v-model="form.staff_id"
                       placeholder="请选择">
              <el-option v-for="(item, index) in allStaffs"
                         :key="index"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="离职原因"
                        prop="resign_reason">
            <el-input v-model="form.resign_reason" placeholder="请输入离职原因，必填"
                      style="width:50%"></el-input>
          </el-form-item>
          <el-form-item label="员工预期离职日期" prop="staff_left_date">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.staff_left_date"
                  style="width: 50%;"></el-date-picker>
          </el-form-item>
          <el-form-item label="最终确定离职日期" prop="final_left_date">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.final_left_date"
                  style="width: 50%;"></el-date-picker>
          </el-form-item>
          <el-form-item label="选择辞职申请状态"
                        prop="status">
            <el-select v-model="form.status"
                       placeholder="请选择">
              <el-option v-for="(item, index) in resignStatus"
                         :key="index"
                         :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editVisible = false">取 消</el-button>
            <el-button type="primary"
                       v-if="form.id > 0"
                       @click="saveEdit">确 定</el-button>
            <el-button type="primary"
                       v-if="form.id == 0"
                       @click="saveAdd">添 加</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { ref, reactive, onMounted } from "vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import {
    resignList,
    staffAll,
    updateStaff,
    addDepartment,
    deleteStaff,
    exportDepartment,
  } from "../../api/index";
  
  export default {
    name: "resign_list",
    setup() {
      const query = reactive({
        name: "",
        status: "",
        pageIndex: 1,
        pageSize: 10,
      });
      const tableData = ref([]);
      const pageTotal = ref(0);
      // 获取表格数据
      const getData = () => {
        resignList(query).then((res) => {
          tableData.value = res.data.data;
          pageTotal.value = res.data.total || 10;
        });
      };
      getData();
  
      // 辞职申请状态
      const resignStatus = ref([
        {
          value: '新建',
          label: '新建'
        }, {
          value: '审批中',
          label: '审批中'
        }, {
          value: '同意',
          label: '同意'
        }, {
          value: '驳回',
          label: '驳回',
        }, {
          value: '归档',
          label: '归档',
        },
      ])
  
      // 查询操作
      const handleSearch = () => {
        query.pageIndex = 1;
        getData();
      };
      // 分页导航
      const handlePageChange = (val) => {
        query.pageIndex = val;
        getData();
      };
  
      // 页面初始化，渲染完dom后获取初始数据绑定到dom上
      onMounted(() => {
        getStaffs();
      });
  
      // 获取员工列表
      const allStaffs = ref([])
      const getStaffs = () => {
        staffAll().then((res) => {
          if (res.code == 0) {
            // 赋值
            allStaffs.value = res.data
            return
          }
          allStaffs.value = []
        });
      };
  
      // 删除操作
      const handleDelete = (row) => {
        // 二次确认删除
        ElMessageBox.confirm("确定要删除吗？", "提示", {
          type: "warning",
        })
          .then(() => {
            let params = {
              id: row.id,
            }
            deleteStaff(params).then((res) => {
              if (res.code == 0) {
                editVisible.value = false
                handleSearch()
                ElMessage.success("删除成功！");
              } else {
                ElMessage.error(res.msg)
              }
            })
          })
          .catch(() => {
            ElMessage.success("取消")
          });
      };
  
      // 表格编辑时弹窗和保存
      const editVisible = ref(false);
      let form = reactive({
        id: 0,
        name: "",
        job_no: "",
        department_id: "",
        leader_id: "",
        company_id: "",
      });
      // 编辑
      let idx = -1;
      const title = ref("");
      const handleEdit = (index, row) => {
        // console.log(row)
        idx = index;
        Object.keys(form).forEach((item) => {
          form[item] = row[item];
        });
        title.value = "编辑辞职申请"
        editVisible.value = true;
      };
  
      // 新增
      const handleAdd = () => {
        getStaffs()
        // 清空form直接信息
        resetForm()
        title.value = "添加辞职申请"
        editVisible.value = true;
      }
  
      // 表单规则
      const rules = {
        staff_id: [
          { required: true, message: "请选择员工", trigger: "blur" },
        ],
        staff_left_date: [
          { required: true, message: "请选择员工预期离职日期", trigger: "blur" },
        ],
        final_left_date: [
          { required: true, message: "请选择最终确定离职日期", trigger: "blur" },
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "blur" },
        ],
        resign_reason: [
          { required: true, message: "请输入离职原因", trigger: "blur" },
        ],
      };
      const formRef = ref(null);
  
      // 提交更新辞职申请
      const saveEdit = () => {
        // 表单校验
        formRef.value.validate((valid) => {
          if (valid) {
            updateStaff(form).then((res) => {
              if (res.code == 0) {
                editVisible.value = false
                handleSearch()
                ElMessage.success("更新成功！");
              } else {
                ElMessage.error(res.msg)
              }
            })
          } else {
            return false;
          }
        });
      };
  
      // 提交新增辞职申请
      const saveAdd = () => {
        // 表单校验
        formRef.value.validate((valid) => {
          if (valid) {
            console.log(form)
            addDepartment(form).then((res) => {
              if (res.code == 0) {
                editVisible.value = false
                handleSearch()
                ElMessage.success("添加成功！");
              } else {
                ElMessage.error(res.msg)
              }
            })
          } else {
            return false;
          }
        });
      };
  
      // 导出excel
      const exportExcel = () => {
        exportDepartment(query).then((res) => {
          if (res.code == 0) {
            editVisible.value = false
            ElMessage.success("成功！");
  
            // 下载文件，原理：拼接url，后端接收到get请求，返回文件信息，实现导出功能
            const a = document.createElement('a')
            a.href = "/api/download?file_path=" + res.data.file_path + "&file_name=" + res.data.file_name
            a.style.display = 'none'
            document.body.appendChild(a)
            a.click() // 点击下载
            document.body.removeChild(a) // 下载完成移除元素
          } else {
            ElMessage.error(res.msg)
          }
        })
      };
  
      // 清空
      const resetForm = function () {
        form["id"] = 0
        form["staff_id"] = ""
        form["resign_reason"] = ""
        form["staff_left_date"] = ""
        form["final_left_date"] = ""
        form["status"] = ""
      }
  
      return {
        query,
        tableData,
        pageTotal,
        editVisible,
        form,
        formRef,
        rules,
        allStaffs,
        handleSearch,
        handlePageChange,
        handleDelete,
        handleEdit,
        handleAdd,
        saveEdit,
        saveAdd,
        title,
        resignStatus,
        exportExcel,
      };
    },
  };
  </script>
  
  <style scoped>
  .handle-box {
    margin-bottom: 20px;
  }
  
  .handle-select {
    width: 120px;
  }
  
  .handle-input {
    width: 300px;
    display: inline-block;
  }
  .table {
    width: 100%;
    font-size: 14px;
  }
  .green {
    color: #67c23a;
  }
  .yellow {
    color: #e6a23c;
  }
  .red {
    color: #ff0000;
  }
  .mr10 {
    margin-right: 10px;
  }
  .table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
  }
  </style>
  